<?php

namespace Method;


use Model\User;

class DefaultRouter
{
    public function handleRequest()
    {
        $requestPath = self::getRequestPath();
        $requestPath = ltrim($requestPath, '/');

        if (!$requestPath) {
            $requestPath = 'Index';
        }

        $this->findController($requestPath);
    }

    private function findController($requestPath)
    {
        list($controller, $method) = explode('/', $requestPath, 2);

        $controller = ucfirst($controller);

        if (is_dir(LIB_PATH . "Controller/{$controller}")) {
            $this->findController($method . '/');
        } elseif (file_exists(LIB_PATH . "Controller/{$controller}.php")) {
            if (!$method) {
                $method = 'index';
            } else {
                $method = lcfirst($method);
            }
            $classname = str_replace('/', '\\', "Controller/{$controller}");

            $controller = new $classname();

            if (method_exists($controller, $method)) {
                $controller->$method();
            }
        } elseif (User::IsUsername($controller) == 1) {
            $classname = str_replace('/', '\\', "Controller/PersonalPage");
            $method = 'jump';
            $username = lcfirst($controller);
            $controller = new $classname();
            $controller->$method($username);
        }
    }

    /**
     * Get request path from server header
     * @return string Path
     */
    public static function getRequestPath()
    {
        if ($_SERVER['PATH_INFO']) {
            $path = trim($_SERVER['PATH_INFO'], '/');
        } else {
            list($path) = explode('?', $_SERVER['REQUEST_URI']);
            $folder = str_replace('/index.php', '', $_SERVER['PHP_SELF']);
            $path = str_replace($folder, '', $path);
        }
        return $path;
    }

}